package Region;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;

public class ZookeeperServiceManager implements Runnable {
    private final String ZNODE = "/db";
    private final String HOST_NAME_PREFIX = "Region_";
    private final String REGION_IP;
    private final String MASTER_IP;
    private final String path;
    private final CuratorFramework client;

    public ZookeeperServiceManager(String REGION_IP, String MASTER_IP) {
        this.REGION_IP = REGION_IP;
        this.MASTER_IP = MASTER_IP;
        this.path = ZNODE + "/" + HOST_NAME_PREFIX + this.REGION_IP;
        this.client = CuratorFrameworkFactory.builder()
                .connectString(this.MASTER_IP + ":2181")
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
    }

    public void run() {
        client.start();
        try {
            if (client.checkExists().forPath(path) != null) {
                // 如果节点存在，先删除这个节点
                client.delete().forPath(path);
            }
            // 至此，节点已经不存在，可以创建一个新节点
            client.create().withMode(CreateMode.EPHEMERAL).forPath(path, REGION_IP.getBytes());
            System.out.println("ZooKeeper节点创建成功");
        } catch (KeeperException.NodeExistsException e) {
            //如果节点在检查存在和尝试删除之间被创建，这将捕获异常。
            System.out.println("节点已存在，但在尝试创建之前已被删除");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            Thread.sleep(Integer.MAX_VALUE); // 保持程序运行，观察节点状态
        } catch (InterruptedException e) {
            client.close();
            throw new RuntimeException(e);
        }
    }
}